#pragma once

#include "mysql.hpp"
#include "vlog.hxx"
#include "vlog-odb.hxx"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <sstream>
#include <algorithm>

namespace zhiang {

class VlogTable {
public:
    using ptr = std::shared_ptr<VlogTable>;
    VlogTable() {}
    VlogTable(const std::shared_ptr<odb::core::database>& db) :_db(db) {}
    // 插入博客
    bool insert(Vlog& vlog) {
        odb::transaction trans(_db->begin());
        try {
            _db->persist(vlog);
            trans.commit();
        } catch(std::exception& e) {
            LOG_ERROR("插入vlog-title[{}]数据失败：{}", vlog.title(), e.what());
            trans.rollback();
            return false;
        }
        return true;
    }
    // 删除博客
    bool remove(const std::string& vlog_id) {
        odb::transaction trans(_db->begin());
        try {
            using query = odb::query<Vlog>;
            using result = odb::result<Vlog>;
            _db->erase_query<Vlog>(query::vlog_id == vlog_id);
            trans.commit();
        } catch(std::exception& e) {
            LOG_ERROR("删除vlog数据-> [{}] ->失败：{}", vlog_id, e.what());
            trans.rollback();
            return false;
        }
        return true;
    }
    std::shared_ptr<Vlog> find(const std::string& vlog_id) {
        odb::transaction trans(_db->begin());
        std::shared_ptr<Vlog> vlog;
        try {               
            using query = odb::query<Vlog>;
            using result = odb::result<Vlog>;
            vlog.reset(_db->query_one<Vlog>(query::vlog_id == vlog_id));
            trans.commit();
        } catch(std::exception& e) {
            LOG_ERROR("查询vlog数据-> [{}] ->失败：{}", vlog_id, e.what());
            trans.rollback();
            return nullptr;
        }
        return vlog;
    }
    // 获取博客列表
    std::vector<Vlog> getVlogList(const std::string& uid) {
        odb::transaction trans(_db->begin());
        std::vector<Vlog> ret;
        try {
            using query = odb::query<Vlog>;
            using result = odb::result<Vlog>;
            result r (_db->query<Vlog>(query::user_id == uid)); 
            for (result::iterator i(r.begin()); i != r.end(); ++i) { 
                ret.push_back(*i);
            }
            trans.commit();
        } catch(std::exception& e) {
            LOG_ERROR("查询申请失败：{}", e.what());
            trans.rollback();
        }
        return ret;
    }

private:
    std::shared_ptr<odb::core::database> _db;
};

}